package net.maku.events.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.AllArgsConstructor;
import net.maku.events.dao.UserJourneyDao;
import net.maku.events.entity.ActivityBriskWalkSiteAnswerConfigEntity;
import net.maku.events.enums.ActivityQuestionTypeEnum;
import net.maku.events.enums.EnableOrNotEnum;
import net.maku.events.service.ActivityBriskWalkSiteAnswerConfigService;
import net.maku.events.service.ActivityContestQuestionService;
import net.maku.events.vo.ActivityBriskWalkSiteAnswerConfigVO;
import net.maku.events.vo.ActivityBriskWalkVO;
import net.maku.events.vo.ActivityContestQuestionVO;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.events.entity.ActivityBriskWalkSiteEntity;
import net.maku.events.vo.ActivityBriskWalkSiteVO;
import net.maku.events.dao.ActivityBriskWalkSiteDao;
import net.maku.events.service.ActivityBriskWalkSiteService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 健步走活动站点
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2025-03-22
 */
@Service
@AllArgsConstructor
public class ActivityBriskWalkSiteServiceImpl extends BaseServiceImpl<ActivityBriskWalkSiteDao, ActivityBriskWalkSiteEntity> implements ActivityBriskWalkSiteService {

    private final ActivityBriskWalkSiteAnswerConfigService activityBriskWalkSiteAnswerConfigService;

    private final ActivityContestQuestionService activityContestQuestionService;

    @Override
    public void setSiteData(ActivityBriskWalkVO activityBriskWalkVO) {
        List<ActivityBriskWalkSiteEntity> walkSiteEntityList = this.list(new LambdaQueryWrapper<ActivityBriskWalkSiteEntity>().eq(ActivityBriskWalkSiteEntity::getWalkActivityId, activityBriskWalkVO.getId()));
        if (CollectionUtils.isEmpty(walkSiteEntityList)) {
            return;
        }
        List<ActivityBriskWalkSiteVO> walkSiteVOList = BeanUtil.copyToList(walkSiteEntityList, ActivityBriskWalkSiteVO.class);
        List<Long> siteIdList = walkSiteVOList.stream().map(ActivityBriskWalkSiteVO::getId).collect(Collectors.toList());
        List<ActivityContestQuestionVO> activityContestQuestionVOList = activityContestQuestionService.findByBusinessIdList(siteIdList, ActivityQuestionTypeEnum.WALK_ACTIVITY.getBusinessType());
        Map<Long, List<ActivityContestQuestionVO>> questionMap;
        if (CollectionUtils.isNotEmpty(activityContestQuestionVOList)) {
            questionMap = activityContestQuestionVOList.stream().collect(Collectors.groupingBy(ActivityContestQuestionVO::getBusinessId));
        } else {
            questionMap = null;
        }
        walkSiteVOList.forEach(item -> {
            if (item.getWhetherOpenAnswer().equals(EnableOrNotEnum.On.getStatus())) {
                item.setAnswerConfigVO(BeanUtil.copyProperties(activityBriskWalkSiteAnswerConfigService.getOne(new LambdaQueryWrapper<ActivityBriskWalkSiteAnswerConfigEntity>().eq(ActivityBriskWalkSiteAnswerConfigEntity::getWalkActivitySiteId, item.getId())), ActivityBriskWalkSiteAnswerConfigVO.class));
                if (ObjectUtils.isNotEmpty(questionMap)) {
                    item.setActivityContestQuestionVOList(questionMap.get(item.getId()));
                }
            }
        });
        activityBriskWalkVO.setActivityBriskWalkSiteList(walkSiteVOList);
    }

    @Override
    public void insertData(Long walkId, List<ActivityBriskWalkSiteVO> voList) {
        shareInsertData(walkId, voList, true);
    }

    /**
     * 共用插入方法
     *
     * @param walkId 健步走id
     * @param voList 站点数组
     */
    private void shareInsertData(Long walkId, List<ActivityBriskWalkSiteVO> voList, boolean isInsert) {
        if (CollectionUtils.isNotEmpty(voList)) {
            if (!isInsert) {
                List<Long> idList = voList.stream().map(ActivityBriskWalkSiteVO::getId).filter(ObjectUtils::isNotEmpty).toList();
                List<ActivityBriskWalkSiteEntity> checkEntityList = this.list(new LambdaQueryWrapper<ActivityBriskWalkSiteEntity>().eq(ActivityBriskWalkSiteEntity::getWalkActivityId, walkId));
                if (CollectionUtils.isNotEmpty(checkEntityList)) {
                    List<Long> alreadyIdList = new java.util.ArrayList<>(checkEntityList.stream().map(ActivityBriskWalkSiteEntity::getId).toList());
                    if (CollectionUtils.isNotEmpty(idList)) {
                        alreadyIdList.removeAll(idList);
                    }
                    if (CollectionUtils.isNotEmpty(alreadyIdList)) {
                        deleteQuestion(alreadyIdList);
                        this.removeByIds(alreadyIdList);
                    }
                }
            }
            for (int i = 0; i < voList.size(); i++) {
                ActivityBriskWalkSiteVO item = voList.get(i);
                ActivityBriskWalkSiteEntity activityBriskWalkSiteEntity = BeanUtil.copyProperties(item, ActivityBriskWalkSiteEntity.class);
                activityBriskWalkSiteEntity.setWalkActivityId(walkId);
                activityBriskWalkSiteEntity.setSiteSort(i + 1);
                this.saveOrUpdate(activityBriskWalkSiteEntity);
                if (item.getWhetherOpenAnswer().equals(EnableOrNotEnum.On.getStatus())) {
                    ActivityBriskWalkSiteAnswerConfigEntity configEntity = BeanUtil.copyProperties(item.getAnswerConfigVO(), ActivityBriskWalkSiteAnswerConfigEntity.class);
                    configEntity.setWalkActivitySiteId(activityBriskWalkSiteEntity.getId());
                    configEntity.setWalkActivityId(walkId);
                    activityBriskWalkSiteAnswerConfigService.saveOrUpdate(configEntity);
                    activityContestQuestionService.save(activityBriskWalkSiteEntity.getId(), ActivityQuestionTypeEnum.WALK_ACTIVITY.getBusinessType(), item.getActivityContestQuestionVOList());
                }
            }
        } else {
            deleteData(Collections.singletonList(walkId));
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateData(Long walkId, List<ActivityBriskWalkSiteVO> voList) {
        //查询出所有的数据
        shareInsertData(walkId, voList, false);
    }

    /**
     * 共用删除方法
     *
     * @param walkIdList 健步走id数组
     */
    private void deleteData(List<Long> walkIdList) {
        List<ActivityBriskWalkSiteEntity> activityBriskWalkSiteEntityList = this.list(new LambdaQueryWrapper<ActivityBriskWalkSiteEntity>().in(ActivityBriskWalkSiteEntity::getWalkActivityId, walkIdList));
        if (CollectionUtils.isNotEmpty(activityBriskWalkSiteEntityList)) {
            List<Long> siteIdList = activityBriskWalkSiteEntityList.stream().map(ActivityBriskWalkSiteEntity::getId).collect(Collectors.toList());
            deleteQuestion(siteIdList);
        }
        this.remove(new LambdaQueryWrapper<ActivityBriskWalkSiteEntity>().in(ActivityBriskWalkSiteEntity::getWalkActivityId, walkIdList));
    }

    /**
     * 删除站点题目、配置
     *
     * @param siteIdList 站点id
     */
    private void deleteQuestion(List<Long> siteIdList) {
        activityContestQuestionService.delete(ActivityQuestionTypeEnum.WALK_ACTIVITY.getBusinessType(), siteIdList);
        activityBriskWalkSiteAnswerConfigService.remove(new LambdaQueryWrapper<ActivityBriskWalkSiteAnswerConfigEntity>().in(ActivityBriskWalkSiteAnswerConfigEntity::getWalkActivitySiteId, siteIdList));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIdList(List<Long> idList) {
        this.remove(new LambdaQueryWrapper<ActivityBriskWalkSiteEntity>().in(ActivityBriskWalkSiteEntity::getWalkActivityId, idList));
        deleteData(idList);
    }

    @Override
    public Map<Long, Long> searchSiteByIdList(List<Long> idList) {
        List<ActivityBriskWalkSiteEntity> walkSiteEntityList = this.list(new LambdaQueryWrapper<ActivityBriskWalkSiteEntity>().in(ActivityBriskWalkSiteEntity::getWalkActivityId, idList));
        if (CollectionUtils.isNotEmpty(walkSiteEntityList)) {
            return walkSiteEntityList.stream().collect(Collectors.groupingBy(ActivityBriskWalkSiteEntity::getWalkActivityId, Collectors.counting()));
        }
        return Map.of();
    }

    @Override
    public Long getCardNumber(Long briskWalkId) {
        return this.count(new LambdaQueryWrapper<ActivityBriskWalkSiteEntity>()
                .eq(ActivityBriskWalkSiteEntity::getWalkActivityId, briskWalkId)
                .isNotNull(ActivityBriskWalkSiteEntity::getCardName));
    }
}